<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://api.feedgraph.com/js/feedgraph.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
//google.setOnLoadCallback(init);

var refreshrate = 1000;

var options = {
width: 900,
			 lineWidth: 1,
			 pointSize: 2,
			 height: 500,
			 curveType: "function",
//			 vAxis: {minValue:0, maxValue:10},
//			 animation: {
//duration: refreshrate,
//			 }
};

var since = 0;
var sincetweet = 0;
var data = null;
var chart = null;
var rate = 0;
var count = 0;
var maxhistory = 200;
var topic = null;
var tweet = null;
function update() {

	feedgraph.getobj("/test/" + topic + "/occurred_in_tweet_obj.json?block=true&since=" + since, addrowshandler);
}

function gettweet() {

	feedgraph.getobj("/test/TWEETS/tweeted_text.json?block=true&since=" + sincetweet, showtweet);
}

function showtweet(arr) {

	tweet.innerHTML = "";
	
	for (var i = 0; i < arr.length; i++) {
		var obj = arr[i];
		try {
			tweet.innerHTML += decodeURIComponent((obj.String+'').replace(/\+/g, '%20')) + "<br>";
		} catch (err) {
		}

		sincetweet = obj.Index;
	}

	gettweet();
}

function addrowshandler(arr) {

	for (var i = 0; i < arr.length; i++) {

		var obj = arr[i];
		var newtime = new Date(obj.Time);
		count = count + 1;

		if (count > 10) for (var k = data.getNumberOfRows() - 1; k >= 0; k--) {

			var postime = data.getValue(k, 0);
			var elapsed = newtime.getTime() / 1000 - postime.getTime() / 1000;

			if (elapsed > 10) {
				var poscount = data.getValue(k, 2);

				rate = (count - poscount) / elapsed;
				break;
			}
		}

		data.addRow([newtime, rate, count]);

		if (data.getNumberOfRows() > maxhistory) {
			data.removeRow(0);
		}

		since = obj.Index;
	}

	drawChart();

}

function drawChart() {
	chart.draw(data, options);
}

function init() {

	topic = window.location.search.substr(1);
	document.getElementById("topic").innerHTML = topic;
	tweet = document.getElementById("tweet");




	chart = new google.visualization.LineChart(
			document.getElementById('linechart'));
	data = new google.visualization.DataTable();
	data.addColumn('datetime', 'time stamp');
	data.addColumn('number', 'tweets/sec');
	data.addColumn({'type':'number', 'role':'ignore'});

	google.visualization.events.addListener(chart, 'ready',
			function() {
				setTimeout("update()", refreshrate);
			});

	update();
	gettweet();
}
</script>
</head>
<body onload="init()">
<h1 id=topic></h1><div id="linechart" style="width: 900px; height: 500px;"></div>
<h1> #olympics #nbc </h1>
<h2 id=tweet></h2>
</body>
</html>
